package com.rf.common.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author rf
 * @Date 2022/4/30
 */
@Component
public class MailUtils {
    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public void contextLoads(String email) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            String codeNum = emailCode();
            System.out.println("验证码为：" + codeNum);
            //标题
            helper.setSubject("您的验证码为："+codeNum);
            //内容
            helper.setText("您好！您在重置您的密码，如果不是您在操作，请忽略！您的验证码为："+"<h2>"+codeNum+"</h2>"+"验证码十分钟之内有效，千万不能告诉别人哦！",true);
            //邮件接收者
            helper.setTo(email);
            //邮件发送者，必须和配置文件里的一样，不然授权码匹配不上
            helper.setFrom("1468430721@qq.com");
            redisTemplate.opsForValue().set(email,codeNum,10, TimeUnit.MINUTES);
            mailSender.send(mimeMessage);
            // 10分钟后过期
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成六位验证码
     */
    public static String emailCode(){
        StringBuilder codeNum = new StringBuilder();
        int [] code = new int[3];
        Random random = new Random();
        //自动生成验证码
        for (int i = 0; i < 6; i++) {
            int num = random.nextInt(10) + 48;
            int uppercase = random.nextInt(26) + 65;
            int lowercase = random.nextInt(26) + 97;
            code[0] = num;
            code[1] = uppercase;
            code[2] = lowercase;
            codeNum.append((char) code[random.nextInt(3)]);
        }
        return String.valueOf(codeNum).toUpperCase();
    }



}
